const express = require('express')
const router = express.Router()
const shop = require('../modle/shop')
const user = require('../modle/user')

router.post('/submit', (req, res) => {
    const { title, price, classify, img, count } = req.body
    shop.create({
        title,
        price,
        classify,
        img,
        count
    })
})

router.post('/addShopCar', (req, res) => {
    //12.
    const { username, id } = req.body
    user.find({ username }).then(data => {
        shop.find({ _id: id }).then(data1 => {
            if (data[0].shopcar.length==0) {
                data[0].shopcar.push(data1[0])
                     user.updateOne({ username }, {
                         shopcar: data[0].shopcar
                     }).then(data2 => {
                         res.send('加入购物车成功')
                     })
            }
             else{
                for (let i = 0; i < data[0].shopcar.length; i++) {
                    if (data[0].shopcar[i]._id == id) {
                        data[0].shopcar[i].count+=1
                        user.updateOne({ username }, {
                            shopcar: data[0].shopcar
                        }).then(data3 => {
                            res.send('加入购物车成功')
                        })
                        return
                    } 
                }
                    data[0].shopcar.push(data1[0])
                        user.updateOne({ username }, {
                            shopcar: data[0].shopcar
                        }).then(data4 => {
                            res.send('加入购物车成功')
                        })
            } 
           
        })
    })
})

router.get('/getShopcar', (req, res) => {
    const { username } = req.body
    user.find({ username }).then(data => {
        res.send(data[0].shopcar)
    })
})

router.post('/delShopcar', (req, res) => {
    const { username, id } = req.body
    user.find({ username }).then(data => {
            data[0].shopcar = data[0].shopcar.filter((item, index) => {
                return item._id != id
            })
            user.updateOne({ username }, {
                shopcar: data[0].shopcar
            }).then(data1 => {
                res.send('删除成功')
            })
    })
})

module.exports = router